from collections import OrderedDict
from .serializers import BookInfoModelSerializer
from .models import BookInfo
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination
# from django_filters.rest_framework import filters
from rest_framework import filters
from rest_framework.exceptions import APIException
from django.db import DatabaseError
from redis import RedisError

class MyPageNumberPagination(PageNumberPagination):
    # 1.指定每页大小
    page_size = 1

    # 2.可以传递参数,手动指定
    page_size_query_param = 'page_size'

    # 3.设置每页最大数量
    max_page_size = 3

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ("haha","哈哈哈"),
            ('results', data)
        ]))

class BookModelViewSet(ModelViewSet):
    """
    list: 获取所有书籍

    create: 创建书籍

    read: 读取书籍
    """

    serializer_class = BookInfoModelSerializer
    queryset = BookInfo.objects.order_by("id").all()

    # 1.局部认证
    # authentication_classes = [SessionAuthentication]

    # 2.局部权限
    # permission_classes = [AllowAny]

    # 3.局部限流
    # throttle_classes = [AnonRateThrottle]

    # 4.可选限流
    # throttle_scope = 'downloads'

    # 5.局部分页
    # pagination_class = LimitOffsetPagination #格式: ?limit=xx 或者 ?limit=xx&offset=xx
    # pagination_class = PageNumberPagination #格式: ?page=4 或者 ?page=4&page_size=100

    # 6.自定义分页
    # pagination_class = MyPageNumberPagination

    # 7.设置过滤字段
    # filterset_fields = ['id', 'btitle',"bread"]

    # 8.排序
    # filter_backends = [filters.OrderingFilter]  #用的是restframe中的,格式: ordering=字段
    # ordering_fields = ['id', 'btitle',"bread"]

    # def list(self, request, *args, **kwargs):
    #
    #     # raise APIException('api异常')
    #     # raise DatabaseError('数据库大出血')
    #     # raise RedisError('redis出问题了')
    #
    #     return super().list(request, *args, **kwargs)


class UploadView(APIView):
    throttle_scope = "uploads"
    def get(self,request):
        return Response("正在拼命....下载中...")